/**
 * @description 执行器-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const oxjs = require('@daelui/oxjs')
const NodeRSA = require('node-rsa')

class Controller extends oxjs.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
  }

  /**
   * @function 执行
  */
  genrsa (action, extender) {
    // 解析数据
    return this.solveAction(action, extender).then(async action => {
      return new Promise((resolve, reject) => {
        let params = action.params || {}
        let units = params.units
        units = units || 1024
        units = parseInt(units)
        units = isNaN(units) ? 1024 : units
        units = units < 16 ? 16 : units
        units = units > 20000 ? 20000 : 1024
        try {
          // 生成一个新的密钥对
          const key = new NodeRSA({ b: units }) // 这里的 b 参数指定了密钥的位数，例如2048位
          // 获取私钥
          const privateKey = key.exportKey('private')
          // 获取公钥
          const publicKey = key.exportKey('public')
          resolve({
            status: 200,
            success: 1,
            data: { public: publicKey, private: privateKey },
            msg: '生成成功'
          })
        } catch (e) {
          reject({ status: 200, success: 0, msg: '生成失败' })
        }
      })
    })
  }
}

module.exports = Controller